#ifndef CHESSDETECTOR_H
#define CHESSDETECTOR_H

#include <QObject>
#include <opencv2/opencv.hpp>
#include <vector>
#include <map>
#include <QImage>
#include <QTimer>
#include "stdshared.h"

struct PieceInfo {
    cv::Point position;
    cv::Point boardCoord;
    cv::Point motorCoords;
    std::string name;
    std::string color;
    int detectionCount = 0;
    bool locked = false;

    PieceInfo(cv::Point pos = cv::Point(), 
            cv::Point motor = cv::Point(), 
            std::string n = "", 
            std::string c = "", 
            int count = 0, 
            bool lock = false)
    : position(pos), motorCoords(motor), name(n), 
        color(c), detectionCount(count), locked(lock) {}
};

class ChessDetector : public QObject {
    Q_OBJECT
public:
    explicit ChessDetector(QObject *parent = nullptr);
    ~ChessDetector();

    cv::Point convertToMotorCoords(int pixel_x, int pixel_y);
    std::tuple<std::vector<cv::Point2f>, std::vector<cv::Point>, cv::Mat, int, int> detectChessboard(cv::Mat image);
    int detectPiece(cv::Mat cell_roi);
    std::vector<PieceInfo> detectOutsidePieces(cv::Mat image);
    void processFrame(cv::Mat frame);
    void packAndPrintData();
    cv::Point getPixelPositionForBoardCoord(int boardX, int boardY);
    bool grabAndProcessFrame();  // 添加新方法
    void setPlayerRole(ROLE role) { m_playerRole = role; }
public slots:
    void startDetection();
    void stopDetection();
    void processVideo();
    void startContinuousVerification(int boardX, int boardY, ROLE expectedRole);

signals:
    void imageProcessed(QImage image);
    void detectionInfo(QString info);
    void verificationResult(int x, int y, bool success);
    void pieceLocked(const std::string& pieceName, int motorX, int motorY);

private:
    cv::VideoCapture cap;
    QTimer* timer;
    cv::Point refCenter;
    std::vector<PieceInfo> boardPieces;
    std::map<std::string, PieceInfo> finalWhitePieces;
    std::map<std::string, PieceInfo> finalBlackPieces;
    const int lockThresholdCount = 10;
    int m_verifyBoardX;
    int m_verifyBoardY;
    ROLE m_expectedRole;
    ROLE m_playerRole; // 存储玩家角色
    bool m_verificationPending;
    QTimer* m_verificationTimer;

};

#endif // CHESSDETECTOR_H